package com.budwk.app.sqfw.services.impl;

import com.budwk.starter.database.service.BaseServiceImpl;
import com.budwk.app.sqfw.models.Sqfw_po_user;
import com.budwk.app.sqfw.services.SqfwPoUserService;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.List;
import java.util.stream.Collectors;

@IocBean(args = {"refer:dao"})
public class SqfwPoUserServiceImpl extends BaseServiceImpl<Sqfw_po_user> implements SqfwPoUserService {
    public SqfwPoUserServiceImpl(Dao dao) {
        super(dao);
    }

    /**
     * 根据系统用户id查询泡泡用户id
     *
     * @param sysUserId 系统用户id
     * @return 泡泡用户id
     */
    @Override
    public String getPopoUserIdBySysUserId(String sysUserId) {
        List<Sqfw_po_user> poUserList = query(Cnd.where("sys_userid", "=", sysUserId));
        if (poUserList.size() == 1) return poUserList.get(0).getPo_userid();
        return null;
    }

    @Override
    public Sqfw_po_user insertSysPopoUserRelationBySys(String sysUserId, String popoUserId, String createUserId) {

        if (StringUtils.isBlank(sysUserId) || StringUtils.isBlank(popoUserId)) return null;

        // 需要做一个校验 根据系统用户id和泡泡用户id进行查询，如果已经存在关系则直接返回
        List<Sqfw_po_user> existList = query(Cnd.where("sys_userid", "=", sysUserId)
                .and("po_userid", "=", popoUserId).and("channel", "=", "sys"));
        if (existList.size() > 0) return existList.get(0);

        Sqfw_po_user sqfwPoUser = new Sqfw_po_user();
        sqfwPoUser.setSys_userid(sysUserId);
        sqfwPoUser.setPo_userid(popoUserId);
        sqfwPoUser.setChannel("sys");
        sqfwPoUser.setCreatedBy(createUserId);
        return insert(sqfwPoUser);
    }

    @Override
    public String getSysUserIdByPopoUid(String popoUid) {
        List<Sqfw_po_user> poUserList = query(Cnd.where("po_userid", "=", popoUid).and("channel", "=", "sys"));
        if (poUserList.size() == 0) return null;

        return poUserList.get(0).getSys_userid();
    }

    @Override
    public List<String> deleteBySysUserId(String userId) {
        List<Sqfw_po_user> poUserList = query(Cnd.where("sys_userid", "=", userId).and("channel", "=", "sys"));
        for (Sqfw_po_user sqfw_po_user : poUserList) {
            delete(sqfw_po_user.getId());
        }
        return poUserList.stream().map(Sqfw_po_user::getPo_userid).collect(Collectors.toList());
    }
}
